import express from 'express';
import cors from 'cors';
import OpenAI from 'openai';
const app = express();
const PORT = 3001;

// 百度AI Studio API配置
const BAIDU_API_BASE = 'https://aistudio.baidu.com/llm/lmapi/v3';
const BAIDU_TOKEN = '9643f8c461f85e668198ec406e476d0bae85cf4d';

// 初始化OpenAI客户端，配置为使用百度API
const openai = new OpenAI({
  apiKey: BAIDU_TOKEN,
  baseURL: BAIDU_API_BASE
});

// 中间件配置
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
  credentials: true
}));

app.use(express.json());
app.use(express.text());

// 健康检查端点
app.get('/health', (req, res) => {
  res.json({ status: 'ok', message: 'Proxy server is running' });
});

// 模型列表API转发
app.get('/v1/models', async (req, res) => {
  try {
    console.log('Fetching models from Baidu API...');
    
    const models = await openai.models.list();
    
    console.log('Models fetched successfully:', models.data.length);
    res.json(models);
  } catch (error) {
    console.error('Error fetching models:', error);
    res.status(500).json({
      error: {
        message: 'Failed to fetch models',
        type: 'proxy_error',
        details: error.message
      }
    });
  }
});

// 聊天完成API转发（支持流式响应）
app.post('/v1/chat/completions', async (req, res) => {
  try {
    console.log('Forwarding chat completion request...');
    
    const requestBody = req.body;
    const isStream = requestBody.stream === true;
    
    // 设置响应头
    if (isStream) {
      res.setHeader('Content-Type', 'text/event-stream');
      res.setHeader('Cache-Control', 'no-cache');
      res.setHeader('Connection', 'keep-alive');
      res.setHeader('Access-Control-Allow-Origin', '*');
    } else {
      res.setHeader('Content-Type', 'application/json');
    }

    if (isStream) {
      // 处理流式响应 - 使用OpenAI SDK
      const stream = await openai.chat.completions.create({
        ...requestBody,
        stream: true
      });
      
      for await (const chunk of stream) {
        // 处理推理内容和正常内容，确保兼容reasoning_content字段
        if (chunk.choices && chunk.choices[0]) {
          const choice = chunk.choices[0];
          let deltaContent = {};
          
          // 检查是否有推理内容（reasoning字段）
          if (choice.delta && choice.delta.reasoning) {
            deltaContent.reasoning = choice.delta.reasoning;
          }
          
          // 检查是否有正常回答内容
          if (choice.delta && choice.delta.content) {
            deltaContent.content = choice.delta.content;
          }
          
          // 如果有内容变化，重新构造chunk
          if (Object.keys(deltaContent).length > 0) {
            const modifiedChunk = {
              ...chunk,
              choices: [{
                ...choice,
                delta: deltaContent
              }]
            };
            res.write(`data: ${JSON.stringify(modifiedChunk)}\n\n`);
          } else {
            res.write(`data: ${JSON.stringify(chunk)}\n\n`);
          }
        } else {
          res.write(`data: ${JSON.stringify(chunk)}\n\n`);
        }
      }
      
      res.write('data: [DONE]\n\n');
      res.end();
    } else {
      // 非流式响应 - 使用OpenAI SDK
      const completion = await openai.chat.completions.create(requestBody);
      
      // 处理reasoning字段兼容性
      if (completion.choices && completion.choices[0]) {
        const choice = completion.choices[0];
        if (choice.message && choice.message.reasoning) {
          // 推理内容已经在reasoning字段中，无需额外处理
        }
      }
      
      res.json(completion);
    }
  } catch (error) {
    console.error('Error in chat completion:', error);
    
    if (!res.headersSent) {
      res.status(500).json({
        error: {
          message: 'Failed to process chat completion',
          type: 'proxy_error',
          details: error.message
        }
      });
    }
  }
});

// 通用API转发（用于其他可能的端点）
// 注意：主要的API端点已通过OpenAI SDK处理
app.all('/v1/*', async (req, res) => {
  try {
    const path = req.path.replace('/v1', '');
    console.log(`Unsupported endpoint: ${req.method} ${path}`);
    
    res.status(404).json({
      error: {
        message: `Endpoint ${path} not supported. Please use /v1/models or /v1/chat/completions`,
        type: 'unsupported_endpoint',
        code: 'endpoint_not_found'
      }
    });
  } catch (error) {
    console.error('Error in generic forwarding:', error);
    res.status(500).json({
      error: {
        message: 'Failed to process request',
        type: 'proxy_error',
        details: error.message
      }
    });
  }
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`\n🚀 Proxy server is running on http://localhost:${PORT}`);
  console.log(`📡 Forwarding requests to: ${BAIDU_API_BASE}`);
  console.log(`🔑 Using token: ${BAIDU_TOKEN.substring(0, 10)}...`);
  console.log(`\n📋 Available endpoints:`);
  console.log(`   GET  /health - Health check`);
  console.log(`   GET  /v1/models - List models`);
  console.log(`   POST /v1/chat/completions - Chat completions`);
  console.log(`\n✅ Ready to handle requests!\n`);
});

// 优雅关闭
process.on('SIGINT', () => {
  console.log('\n🛑 Shutting down proxy server...');
  process.exit(0);
});